<template>
  <div>
    <el-form
      :model="form"
      :rules="rules"
      ref="form"
      label-width="140px"
      label-position="left"
      class="h_full p-20 of_auto pb-60"
    >
      <div class="draw-box">基本信息</div>
      <el-form-item label="姓名：" prop="name">
        <el-input
          v-model="form.name"
          size="small"
          placeholder="请输入子账号名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="子账号：" prop="subname">
        <div class="flex">
          <el-input
            :value="phone+'@'"
            size="small"
            style="width: 132px"
            class="mr-10"
          ></el-input>
          <el-input
            v-model="form.subname"
            size="small"
            placeholder="请补充子账号名"
            style="width: calc(100% - 142px)"
          ></el-input>
        </div>
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input
          v-model="form.password"
          size="small"
          placeholder="请输入密码"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item label="可用席位数：" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="0">不限</el-radio>
          <el-radio :label="1">
            <el-input
              :disabled="!form.status"
              v-model="form.num"
              size="small"
              maxlength="10"
              @input="(e) => (form.num = integerZeroFn(e))"
              placeholder="请输入"
              style="width: 88px"
            ></el-input>
            个
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <div class="draw-box">账号权限</div>
      <el-form-item label="角色类型：" prop="role">
        <el-select
          v-model="form.role"
          size="small"
          placeholder="请选择"
          class="w_full"
        >
          <el-option v-for="(item,index) in roleList" :key="index" :label="item.roleName" :value="item.id"></el-option>
        </el-select>
        <div class="forminfo c_text3 f-14">不同角色对应不同功能的使用权限</div>
      </el-form-item>
      <el-form-item label="权限范围：" prop="permission" class="mb-0">
        <el-radio-group v-model="form.permission">
          <el-radio :label="1" class="c_text2">仅自己</el-radio>
          <el-radio :label="2" class="c_text2"
            >全部子账号
            <el-tooltip
              effect="dark"
              placement="top"
              popper-class="commtooltip"
            >
              <div slot="content">
                统计分组下所有企微号（含分组下其<br />他子账号登录的企微号）的登录数据
              </div>
              <svg-icon icon-class="iquestion" class-name="c_text2 f-14 ml-5" />
            </el-tooltip>
          </el-radio>
          <el-radio :label="3" class="c_text2">自定义范围</el-radio>
        </el-radio-group>
        <div class="forminfo c_text3 f-14">
          可查看/管理以下勾选分组中所有子账号登录的企微号
        </div>
      </el-form-item>
      <el-form-item v-if="form.permission == 3" label="" prop="permission">
        <div class="scopgroups">
          <el-tree
            default-expand-all
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </div>
      </el-form-item>
    </el-form>
    <div class="drawfooter flexend">
      <el-button size="small" @click="handleClose">取消</el-button>
      <el-button type="primary" plain size="small" @click="submit(2)"
        >保存并继续添加</el-button
      >
      <el-button type="primary" size="small" @click="submit(1)"
        >确认保存</el-button
      >
    </div>
  </div>
</template>

<script>
import { getRoleList } from "@/api/role";
import {getsubUserGroupList, addSubUser, editSubUser } from "@/api/user";
import { mapGetters } from 'vuex';
export default {
  data() {
    return {
      form: {
        name: "",
        subname: "",
        password: "",
        status: 0,
        num: "",
        role: "",
        permission: 1,
      },
      rules: {
        name: [
          { required: true, message: "请输入子账号名称", trigger: "blur" },
        ],
        subname: [
          { required: true, message: "请补充子账号名", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请补充子账号名", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "用户密码长度必须介于 6 和 20 之间",
            trigger: "blur",
          },
        ],
        status: [
          { required: true, message: "请选择可用席位数", trigger: "change" },
        ],
        role: [{ required: true, message: "请选择角色", trigger: "change" }],
        permission: [
          { required: true, message: "请选择权限", trigger: "change" },
        ],
      },
      roleList:[],
      defaultProps: {
        children: "children",
        label: "groupName",
      },
      // 菜单列表
      menuOptions: [],
    };
  },
  computed:{
    ...mapGetters(['phone'])
  },
  created(){
    this.getRoleList()
    this.getUserGroupList()
    console.log('tableItem:', this.tableItem)
    if(this.tableItem){
      this.form.name = this.tableItem.clientUserName
      this.form.subname = this.tableItem.clientUserAccount.split('@')[1]
      this.form.password = this.tableItem.clientUserPassword
      this.form.status = this.tableItem.wxCount==-1?0:1
      if(this.tableItem.wxCount!==-1)
        this.form.num = this.tableItem.wxCount
      this.form.permission = this.tableItem.scope
      
    }
  },
  props:{
    groupId:{
      required:true,
      default:""
    },
    tableItem:{
      default:null
    }
  },
  methods: {
    // 角色列表
    getRoleList() {
      getRoleList().then((res) => {
        this.roleList = res.rows;
        if(this.tableItem){
          this.form.role = this.tableItem.clientUserRoleId
        }
      });
    },

    // 用户分组列表
    getUserGroupList(){
      getsubUserGroupList().then(res=>{
        this.menuOptions = this.handleTree([{groupName:'全部',id:-1}].concat(res.rows),'id','parentGroupId')
        if(this.tableItem){
          if(this.form.permission == 3){
            // this.refs.menu.
            let checkedKeys = this.tableItem.scopeGroupIds.split(',')
            checkedKeys.forEach((v) => {
              this.$nextTick(()=>{
                this.$refs.menu.setChecked(v, true ,false);
              })
            })
          }
        }
      })
    },

    /** 查询菜单树结构 */
    // getMenuTreeselect() {
      // getsubUserGroupList().then(res=>{
      //   this.roleList = this.handleTree(res.rows,'id','parentGroupId')
      //   this.loading = false
      // })
      // menuTreeselect().then((response) => {
      //   this.menuOptions = response.data;
      // });
    // },

    // 所有树形节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的部门节点
      // let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      // checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },

    submit(type) {
      this.$refs.form.validate((valid) => {
        if (!valid) return;
        let params = {
          clientUserName:this.form.name,
          clientUserAccount: this.phone+'@'+this.form.subname,
          clientUserPassword: this.form.password,
          wxCount:this.form.status === 0?-1:this.form.num,
          clientUserRoleId:this.form.role,
          scope: this.form.permission,
          clientUserGroupId: this.groupId
        }
        if(this.form.permission == 3){
          let arr = this.getMenuAllCheckedKeys()
          if(!arr.length){
            this.$message.warning('请选择权限范围')
            return
          }
          params.scopeGroupIds = arr.join(',')
        }

        if(this.tableItem){
          // 修改
          params.id = this.tableItem.id
          editSubUser(params).then(response => {
            this.$modal.msgSuccess("编辑成功");
            if(type==1){
              this.$emit("close",1);
            }
          })
        }else{
          // 添加
          addSubUser(params).then(response => {
            this.$modal.msgSuccess("添加成功");
            if(type==1){
              this.$emit("close",1);
            }
          });
        }

        
      });
    },

    handleClose() {
      this.$emit("close");
    },
  },
};
</script>
<style lang="scss" scoped>
.forminfo {
  line-height: 26px;
}
.scopgroups {
  background: #f5f5f5;
  padding: 10px;
  position: relative;
}
</style>